package com.gexin.service.order;

import com.gexin.common.model.ApiResponse;
import com.gexin.model.agent.Agent;
import com.gexin.model.agent.AgentAccountLog;
import com.gexin.model.order.Order;
import com.gexin.model.order.OrderCart;
import com.gexin.model.order.OrderItem;
import com.gexin.model.weixin.WeixinUser;
import com.jfinal.plugin.activerecord.Page;

import java.util.Date;
import java.util.List;

/**
 * @author 黎峻
 * @Title: 订单相关联通用方法
 * @date 2019/9/2510:45
 */
public class OrderService {


	public static OrderService dao = new OrderService();

	/**
	 * 添加商品到购物车
	 * @param productId
	 * @param skuTxt
	 * @param skuId
	 * @param authUser
	 */
	public ApiResponse addProductInCart(Integer productId , String skuTxt , String skuId , WeixinUser authUser) {

		OrderCart orderCart =OrderCart.dao.findByUserIdAndSkuId(authUser.getId(),skuId);
		ApiResponse apiResponse = new ApiResponse(false,"未知错误!");
		if(orderCart==null){
			orderCart = new OrderCart();
			orderCart.setProductId(productId);
			orderCart.setSkuId(skuId);
			orderCart.setSkuTxt(skuTxt);
			orderCart.setUserId(authUser.getId().toString());
			orderCart.setCreatetime(new Date());
			orderCart.setNums(1);
			boolean save = orderCart.save();
			apiResponse = new ApiResponse(save,save?"添加成功!":"添加失败!");
		}else{
			orderCart.setNums(orderCart.getNums()+1);
			orderCart.setCreatetime(new Date());
			boolean update = orderCart.update();
			apiResponse = new ApiResponse(update,update?"添加成功!":"添加失败!");
		}
		return apiResponse;

	}

	public Page<Order> findAgentOrders(Integer agentId, Integer page, Integer pageSize, String startTime, String endTime, String state, String type, String cityId) {
		Page<Order> paginate = Order.dao.findAgentOrders(agentId , page , pageSize, startTime,  endTime,  state,  type,  cityId);
		List<Order> orders = paginate.getList();
		for (Order order : orders) {
			List<OrderItem> orderItems = OrderItem.dao.getItembyId(order.getId());
			order.put("item",orderItems);
		}
		return paginate;
	}



	public Page<Order> findErJiAgentOrders(Integer agentId, Integer page, Integer pageSize, String startTime, String endTime, String state, String type) {
		Agent agent = Agent.dao.findById(agentId);
		Page<Order> paginate =null;

		if(Agent.TYPE_AREA.equals(agent.getType())){
			paginate = Order.dao.findAreaAgentOrders(agentId , page , pageSize, startTime,  endTime,  state,  type);

		}else{
			paginate = Order.dao.findErJiAgentOrders(agentId , page , pageSize, startTime,  endTime,  state,  type);

		}
		List<Order> orders = paginate.getList();
		for (Order order : orders) {
			List<OrderItem> orderItems = OrderItem.dao.getItembyId(order.getId());
			AgentAccountLog agentAccountLog = AgentAccountLog.dao.findFirst("select * from  t_agent_account_log where agent_id=? and order_id=?",agentId,order.getId());
			order.put("agentAccountLog",agentAccountLog);
			order.put("item",orderItems);
		}

		System.out.println(paginate);
		return paginate;
	}
}
